package com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtp.listener;

import com.alibaba.fastjson.JSONObject;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtp.dto.OrderDTO;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtp.meassage.OrderMessage;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtp.service.PointsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * 订单监听
 *
 * @author ziyucoding
 * @date 2023-04-03
 **/
@Component
public class OrderListener {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PointsService pointsService;

    @StreamListener(OrderSink.ORDER_INPUT)
    public void onMessage(@Payload org.springframework.messaging.Message<OrderMessage> message) {
        logger.info("消费者线程监听到消息。");
        logger.info("开始处理订单数据，准备增加积分....");
        // 从消息 Header 中解析到 order 参数，并使用 JSON 反序列化
        OrderDTO order = JSONObject.parseObject(message.getHeaders().get("order", String.class),
                OrderDTO.class);
        pointsService.increasePoints(order);
    }

}
